//
//  NearFoodViewController.m
//  Delicious2
//
//  Created by dllo on 16/1/15.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "NearFoodViewController.h"
#import "EatShowViewController.h"

#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件

#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件

#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件

#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件

#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件

#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件

#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件

#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件

@interface NearFoodViewController ()<BMKMapViewDelegate, BMKPoiSearchDelegate, BMKLocationServiceDelegate, UITableViewDataSource, UITableViewDelegate>
//地图类
@property (nonatomic, strong) BMKMapView *mapView;
//搜索类
@property (nonatomic, strong)  BMKPoiSearch *poisearch;
//定位类
@property (nonatomic, strong) BMKLocationService *locService;
//大头针类
@property (nonatomic, strong) BMKPointAnnotation* annotation;

//当前位置经纬度
@property (nonatomic, assign) double latitude;
@property (nonatomic, assign) double longitude;

//大头针数组
@property (nonatomic, strong) NSMutableArray *annotationDataSource;
//poi检索返回数组
@property (nonatomic, strong) NSArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong)  MBProgressHUD *HUD;



@end

@implementation NearFoodViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"周边美食";
self.annotationDataSource = [NSMutableArray arrayWithCapacity:0];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
  
    UIBarButtonItem *itemSearch = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ImageNearSearech"] style:UIBarButtonItemStylePlain target:self action:@selector(rightSearchButtonDidPress:)];
    UIBarButtonItem *itemResult = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ImageNearResult"] style:UIBarButtonItemStylePlain target:self action:@selector(rightResultButtonDidPress:)];
    self.navigationItem.rightBarButtonItems = @[itemResult, itemSearch];
    
    //1.初始化地图
    self.mapView = [[BMKMapView alloc]initWithFrame:self.view.bounds];
    self.mapView.delegate = self;
    // 设置地图级别
    [_mapView setZoomLevel:18];
    _mapView.isSelectedAnnotationViewFront = YES;
    [self.view addSubview:self.mapView];
    
    //初始化大头针
    self.annotation = [[BMKPointAnnotation alloc]init];

    
    //2.定位
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];

    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText;
    HUD.yOffset = HEIGHT / 3;
    HUD.margin = 5;
    HUD.cornerRadius = 5;
    HUD.labelText = @"点击定位,搜索周边美食";
    [HUD hide:YES afterDelay:3];
}



//建立tableView
- (void)creatTableView {
    if (!self.tableView) {
        CGFloat maxH = MIN(HEIGHT - 113,self.dataSource.count * 44);
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH / 3 * 2 , 64, WIDTH / 3, maxH) style:UITableViewStyleGrouped];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
        self.tableView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:self.tableView];
    }
}

//tableVi协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    
    if (self.dataSource.count) {
        BMKPoiInfo *poinInfo = self.dataSource[indexPath.row];
        cell.textLabel.text = poinInfo.name;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BMKPoiInfo *poinInfo = self.dataSource[indexPath.row];
    
    double latitude = poinInfo.pt.latitude;
    double longitude = poinInfo.pt.longitude;
    CLLocationCoordinate2D coor;
    coor.latitude = latitude;
    coor.longitude = longitude;
    //改变地图中心点
    self.mapView.centerCoordinate = coor;
    tableView.hidden = YES;
    
    //弹出气泡
    BMKPinAnnotationView *newAnnotationView = self.annotationDataSource[indexPath.row + 1];
    [newAnnotationView setSelected:YES animated:YES];
    newAnnotationView.paopaoView.hidden = NO;
    [_mapView mapForceRefresh];

}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    //取消弹出气泡
    BMKPinAnnotationView *newAnnotationView = self.annotationDataSource[indexPath.row + 1];
    [newAnnotationView setSelected:NO animated:YES];
    newAnnotationView.paopaoView.hidden = YES;
    [_mapView mapForceRefresh];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

//7.搜索结果
- (void)rightResultButtonDidPress:(UIButton *)button {
    if (self.dataSource.count) {
        if (self.tableView.hidden) {
            self.tableView.hidden = NO;
        } else {
            self.tableView.hidden = YES;
        }
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先定位" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}
//3.点击执行定位
- (void)rightSearchButtonDidPress:(UIButton *)button {
    [self searchPOI];
}

//处理位置坐标更新(位置改变就执行)
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    self.latitude = userLocation.location.coordinate.latitude;
    self.longitude = userLocation.location.coordinate.longitude;
    
}



//6.设置大头针属性(在执行插入大头针时执行，每次插入一个便执行一次)
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation {
   if (self.annotationDataSource.count > 51) {
       [self.annotationDataSource removeAllObjects];
   }
    
    
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        //是否显示选中（是否弹出信息）
        newAnnotationView.selected = NO;
        // 设置该标注点动画显示
        newAnnotationView.animatesDrop = YES;
        //添加数组
        [self.annotationDataSource addObject:newAnnotationView];
        //设置标签
        newAnnotationView.tag = self.annotationDataSource.count - 1;
         //大头针颜色
        if ([annotation isEqual:self.annotation]) {
            newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        } else {
            newAnnotationView.pinColor = BMKPinAnnotationColorRed;
        }
//        NSLog(@"%ld", self.annotationDataSource.count);
        return newAnnotationView;
    }
    return nil;
}


//5.实现PoiSearchDeleage处理回调结果
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error {
    self.HUD.hidden = YES;
    if (error == BMK_SEARCH_NO_ERROR) {
        
        self.dataSource = [NSArray arrayWithArray:poiResultList.poiInfoList];
        
        for (BMKPoiInfo *poinInfo in self.dataSource) {
            BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
            CLLocationCoordinate2D coor;
            coor.latitude = poinInfo.pt.latitude;
            coor.longitude = poinInfo.pt.longitude;
            annotation.coordinate = coor;
            annotation.title = poinInfo.name;
            annotation.subtitle = poinInfo.address;
            [_mapView addAnnotation:annotation];
        }
        [_mapView mapForceRefresh];
        //创建视图
        [self creatTableView];
        self.tableView.hidden = YES;
        [self.tableView reloadData];
    } else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有搜索到结果,请重新搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
}
//提示框点击事件(定位失败的时候弹出,是上面UIAlertView的点击事件)
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex) {
        [self searchPOI];
        alertView.hidden = YES;
    }
}

//4.搜索兴趣点
- (void)searchPOI {
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    //初始化检索对象
    self.poisearch =[[BMKPoiSearch alloc]init];
    self.poisearch.delegate = self;
    
    //范围内检索，请求发送成功返回YES，请求发送失败返回NO
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
    option.pageIndex = 0;
    option.pageCapacity = 50;
    option.location = CLLocationCoordinate2DMake(self.latitude, self.longitude);
    option.radius = 1000; //检索范围 m
    option.keyword = @"美食";
    BOOL flag = [self.poisearch poiSearchNearBy:option];
    if(flag){
        self.HUD.labelText = @"正在定位中...";
    }
    else{
        self.HUD.labelText = @"定位失败！！！";
    }
    
    //插大头针
    CLLocationCoordinate2D coor;
    coor.latitude = self.latitude;
    coor.longitude = self.longitude;
    _annotation.coordinate = coor;
    _annotation.title = @"当前位置";
    [_mapView addAnnotation:_annotation];
    _mapView.centerCoordinate = coor;

}


//8.弹出气泡点击事件
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKPinAnnotationView *)view{
    //去除当前位置点击
    if (!view.tag == 0) {
        BMKPoiInfo *poinInfo = self.dataSource[view.tag - 1];
        //跳转详情页面
        [self searPOIDetail:poinInfo];
    }
    
}
//10.详情查询结果（拿到URL自动跳转）
-(void)onGetPoiDetailResult:(BMKPoiSearch *)searcher result:(BMKPoiDetailResult *)poiDetailResult errorCode:(BMKSearchErrorCode)errorCode
{
    if(errorCode == BMK_SEARCH_NO_ERROR){
        //在此处理正常结果
        
        //跳转详情界面
        EatShowViewController *showVC = [[EatShowViewController alloc] init];
        showVC.urlString = poiDetailResult.detailUrl;
        showVC.urlKind = @"附近美食";
        showVC.urlTitle = poiDetailResult.name;
        showVC.urlImage = @"http://i2.s1.dpfile.com/pc/9dabe9d641fa83e31d0d4714981e9ef4(700c700)/thumb.jpg";
        
        [self.navigationController pushViewController:showVC animated:YES];
    }
}

//9.POI详情检索
- (void)searPOIDetail:( BMKPoiInfo *)poinInfo{
    //POI详情检索
    BMKPoiDetailSearchOption* option = [[BMKPoiDetailSearchOption alloc] init];
    //POI搜索结果中获取的uid
    option.poiUid = poinInfo.uid;
    BOOL flag = [_poisearch poiDetailSearch:option];
    if(flag) {
        //详情检索发起成功
    } else {
        self.HUD.labelText = @"进入失败,请重新进入";
        [self.HUD hide:YES afterDelay:3];
    }
}


//取消抽屉滑动
- (void)viewWillAppear:(BOOL)animated {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    DrawerViewController *drawerVC = delegate.drawerVC;
    drawerVC.needSwipeShowMenu = NO;
    
}
//开启抽屉滑动
- (void)viewWillDisappear:(BOOL)animated {
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    DrawerViewController *drawerVC = delegate.drawerVC;
    drawerVC.needSwipeShowMenu = YES;
    
}
#pragma mark - 内存泄露
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
